<?php


namespace app\privatearea\controller\astro;


use app\common\cachemodel\privatearea\PrivateAreaContentCheck;
use app\common\cachemodel\privatearea\PrivateAreaGoods;
use app\common\cachemodel\privatearea\PrivateAreaOrders;
use app\common\cachemodel\privatearea\PrivateAreaQuestionInfo;
use app\common\lib\AliOss;
use app\common\lib\Util;
use app\privatearea\controller\AstroAuth;
use think\Db;
use think\Env;
use think\Log;

class Question extends AstroAuth
{

    public function questionInfo()
    {
        $sn = input('sn/s', '');

        $goodModel = new PrivateAreaGoods();
        $questionInfoModel = new PrivateAreaQuestionInfo();

        $goodInfo = $goodModel->getPrivateAreaGoodInfo($sn, ['type', 'info_type', 'name', 'order_num']);

        if (!$goodInfo)
        {
            return show(config('code.success'), '请求成功', ['status' => 4]);
        }

        $orderInfo = (new PrivateAreaOrders())->getInfoById($goodInfo['order_num'], ['status', 'qid']);

        if ($orderInfo['status'] != 2 && $this->request->header('app-type') !== 'manage')
        {
            return show(config('code.success'), '请求成功', ['status' => 4]);
        }

        $questionInfo = $questionInfoModel->getPrivateAreaQuestionInfo($orderInfo['qid']);

        if ($questionInfo['astro_id'] !== (int)$this->astro['id'])
        {
            return show(config('code.success'), '请求成功', ['status' => 4]);
        }

        $resData = $questionInfoModel->questionIndeResetShow($questionInfo, $goodInfo, true);

        $statusConfig = [
            4 => 0,
            5 => 1,
            6 => 2,
            7 => 3,
            8 => 4,
        ];
        if ($questionInfo['answer_content'])
        {
            $checkFailDes = '';
            if ($questionInfo['status'] === 6)
            {
                $checkFailDes = (new PrivateAreaContentCheck())->where('qid', $orderInfo['qid'])->order('id desc')->value('desc');
            }
            $files = json_decode($questionInfo['answer_content'], true);
            $aliOss = AliOss::getInstance();
            foreach ($files as $index => $fileItem)
            {
//                $files[$index]['url'] = $aliOss->getAuth($fileItem['url']);
                $url = $aliOss->getAuth($fileItem['url']);
                $url = str_replace('http://zhunle.oss-cn-beijing.aliyuncs.com', 'https://oss.goddessxzns.com', $url);
                $files[$index]['url'] = $url;
                $files[$index]['path'] = $fileItem['url'];
            }

            $resData[] = [
                'type' => 6,
                'title' => '上传回复',
                'des' => '支持格式：doc、docx、pdf、mp4、avi、mov、rm、jpg、jpeg、png',
                'upload_info' => [
                    'time' => date('Y-m-d H:i:s', $questionInfo['last_submit_time']),
                    'files' => $files,
                    'check_fail_des' => $checkFailDes
                ]
            ];
        } else if (0 === $statusConfig[$questionInfo['status']])
        {//未回答
            $resData[] = [
                'type' => 6,
                'title' => '上传回复',
                'des' => '支持格式：doc、docx、pdf、mp4、avi、mov、rm、jpg、jpeg、png',
            ];
        }

        return show(config('code.success'), '请求成功', [
            'status' => $statusConfig[$questionInfo['status']],
            'list' => $resData,
            'order_id' => $goodInfo['order_num']
        ]);
    }

    /**
     * 提交解答信息
     */
    public function submitAnswer()
    {
        $orderId = input('order_id/s', '');
        $answerContrent = input('answer_content/s', '');

        if (!$orderId || !$answerContrent)
        {
            return show(config('code.error'), '请求异常！请稍后再试～');
        }

        $answerContrentArr = json_decode($answerContrent, true);
        if (!$answerContrentArr || count($answerContrentArr) > 6)
        {
            return show(config('code.error'), '答案数据异常，提交结果失败！');
        }

        foreach ($answerContrentArr as $value)
        {
            if (!isset($value['type'], $value['url'], $value['file_name']) || !in_array($value['type'], [1, 2, 3, 4], false) || empty($value['url']) || empty($value['file_name']))
            {
                return show(config('code.error'), '答案数据异常，提交结果失败！');
            }
        }

        $orderInfo = (new PrivateAreaOrders())->getInfoById($orderId, ['status', 'qid']);
        if (!$orderInfo || $orderInfo['status'] !== 2)
        {
            return show(config('code.error'), '请求异常！请稍后再试～');
        }
        $questionInfoModel = new PrivateAreaQuestionInfo();

        $questionInfo = $questionInfoModel->getPrivateAreaQuestionInfo($orderInfo['qid']);
        if ($questionInfo['astro_id'] !== (int)$this->astro['id'])
        {
            return show(config('code.error'), '请求异常！请稍后再试～');
        }
        if ($questionInfo['status'] === 5)
        {
            return show(config('code.error'), '等待审核中，提交结果失败！');
        }
        if (!in_array($questionInfo['status'], [4, 6], true))
        {
            return show(config('code.error'), '状态异常，提交结果失败！');
        }

        try
        {
            $answerContrentCheckData = [
                'status' => 1,
                'qid' => $orderInfo['qid'],
                'extend' => $answerContrent,
                'create_time' => $this->request->time()
            ];

            $checkId = (new PrivateAreaContentCheck())->insertGetId($answerContrentCheckData);
            $res = $questionInfoModel->updateUserQuestionData($orderInfo['qid'], [
                'answer_content' => $answerContrent,
                'last_submit_time' => $this->request->time(),
                'status' => 5
            ]);

            if ($res)
            {
                $goodModel = new PrivateAreaGoods();
                $goodInfo = $goodModel->getPrivateAreaGoodInfo($questionInfo['hash'], ['type', 'name', 'aid']);

                $env = Env::get('host.name', 'local');
                $adminName = Db::table('wechatadmin.system_admin_user')->where('id', $goodInfo['aid'])->value('username');
                Util::resDingDingMsgSend('[' . $env . ']审核提醒，占星师已回复，请注意跟进',
                    "任务ID：{$orderInfo['qid']} \r\n" .
                    "商品名称：{$goodInfo['name']} \r\n" .
                    "专属客服：{$adminName}",
                    Env::get('host.admin_domain') . '/admin/private_area.task/task_check_list.html?id=' . $orderInfo['qid'], 'private_area', 6);
                // 添加审核超时【12小时】检测队列
                Util::queuePush('private_area_answer_check', [
                    'id' => $checkId,
                    'good_type' => $goodModel->goodTypeName[$goodInfo['type']],
                    'good_name' => $goodInfo['name'],
                    'admin_name' => $adminName
                ], 43200);

                return show(config('code.success'), '提交结果成功');
            } else
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
        }
        catch (\Exception $e)
        {
            Log::write('私域H5 答案提交异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
